package code.class2;


import common.ArrayUtils;

/**
 * 二分查找
 * https://leetcode.cn/problems/find-first-and-last-position-of-element-in-sorted-array/
 * 在排序数组中查找元素的第一个和最后一个位置
 */
public class Code08_searchRange {

    public static void main(String[] args) {
        int[] arr = {5, 7, 7, 8, 8, 10};
        int target = 8;
        int[] ans = searchRange(arr, target);
        ArrayUtils.printArr(ans);
    }

    public static int[] searchRange(int[] arr, int target) {
        return new int[]{findLeft(arr, target), findRight(arr, target)};
    }

    public static int findLeft(int[] arr, int target) {
        int ans = -1, mid, l = 0, r = arr.length - 1;
        while (l <= r) {
            mid = l + ((r - l) >> 1);
            if (arr[mid] == target) {
                ans = mid;
                r = mid -1;
            } else if (arr[mid] < target) {
                l = mid + 1;
            } else {
                r = mid - 1;
            }
        }
        return ans;
    }

    public static int findRight(int[] arr, int target) {
        int ans = -1, mid, l = 0, r = arr.length - 1;
        while (l <= r) {
            mid = l + ((r - l) >> 1);
            if (arr[mid] == target) {
                ans = mid;
                l = mid +1;
            } else if (arr[mid] < target) {
                l = mid + 1;
            } else {
                r = mid - 1;
            }
        }
        return ans;
    }

}